"""
    topology_optimization.py - Minimize the compliance
"""

import BLES6
from openmdao.main.api import Assembly, Component
from openmdao.main.datatypes.api import Instance, Int
from openmdao.main.datatypes.api import Float

class Initialise(Component):
    maxIteration = Int(0, iotype='in')

    def execute(self):
        self.maxIteration = BLES6.initialise(1,"cant.txt")


class Analysis(Component):
   
    displacement = Float(0., iotype='out', units='kW', desc='')
    
    def execute(self):
        itt = 1
        self.ana = BLES6.analysis(itt)

class Sensitivity(Component):
    convergence = Int(0, iotype='in')
    
    def execute(self):
        self.convergence = BLES6.sensitivity()



class Output(Component):

    def execute(self):
        BLES6.output()



class Optimize(Component):
    displacement = Float(0., iotype='out', units='kW', desc='')
    def execute(self):
        Init = Initialise()
        Sen = Sensitivity()
        Out = Output()
        itt = 0
        
        displacement=0.0

        Init.execute()

        while itt < Init.maxIteration:
            (displacement) = BLES6.analysis(itt)
    
            Sen.execute()
    
            if Sen.convergence == 1:
                break
    
            BLES6.optimize()
    
            itt+= 1

        self.displacement = displacement[0]
        
        print 'Displacement: ', self.displacement
        
        Out.execute()

class Optimization(Assembly):
    
    def configure(self):
        self.add('initialise', Initialise())
        self.add('sensitivity', Sensitivity())
        self.add('optimize', Optimize())
        self.add('output', Output())
        
        self.driver.workflow.add(['initialise','optimize'])

if __name__ == "__main__":
    
    opt_problem = Optimization()
    
    opt_problem.run()
    
    print 'Displacement: ', Optimize.displacement


